import logging
from django.utils import timezone
from django.db.models import Q, Count
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth import authenticate, login
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from drf_spectacular.utils import extend_schema, OpenApiParameter
from drf_spectacular.types import OpenApiTypes

from .models import Review
from .serializers import (
    ReviewSerializer, 
    ReviewCreateSerializer,
    ReviewUpdateSerializer
)
from .permissions import IsAdminOrOwner, IsReviewer
from notification_app.models import Notification

logger = logging.getLogger(__name__)


# 前端页面视图
def review_login(request):
    """审核员登录页面"""
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None and user.is_staff:
            login(request, user)
            return redirect('review_app_frontend:review_index')
        else:
            return render(request, 'review/login.html', {'error': '用户名或密码错误'})
    else:
        return render(request, 'review/login.html')


@login_required
@user_passes_test(lambda u: u.is_staff)
def review_index(request):
    """审核管理主页"""
    return render(request, 'review/index.html')


@login_required
@user_passes_test(lambda u: u.is_staff)
def review_list(request):
    """审核列表页面"""
    return render(request, 'review/list.html')


@login_required
@user_passes_test(lambda u: u.is_staff)
def review_detail(request, pk):
    """审核详情页面"""
    return render(request, 'review/detail.html')


class ReviewViewSet(viewsets.ModelViewSet):
    """
    审核管理API
    
    提供资质审核的完整功能，包括用户资质审核和车辆资质审核。
    
    功能说明：
    * 获取待审核列表 - GET /api/admin/review/pending/
    * 获取审核详情 - GET /api/admin/review/{id}/
    * 提交审核结果 - POST /api/admin/review/{id}/approve/
    * 获取审核历史 - GET /api/admin/review/history/
    
    权限要求：
    * 只有管理员可以访问审核接口
    
    通知类型说明：
    * ORDER ('order') - 订单通知
    * PAYMENT ('payment') - 支付通知
    * SYSTEM ('system') - 系统通知
    * MESSAGE ('message') - 消息通知
    
    审核完成后，系统会自动向相关用户发送系统通知(SYSTEM)。
    """
    
    queryset = Review.objects.all()
    serializer_class = ReviewSerializer
    permission_classes = [IsAuthenticated, IsAdminOrOwner]
    
    def get_serializer_class(self):
        """根据操作选择序列化器"""
        if self.action in ['create', 'pending']:
            return ReviewCreateSerializer
        elif self.action in ['update', 'partial_update']:
            return ReviewUpdateSerializer
        return self.serializer_class
    
    def get_queryset(self):
        """根据用户角色过滤查询集"""
        queryset = Review.objects.all()
        
        # 只有管理员可以查看所有审核记录
        if not self.request.user.is_staff:
            queryset = queryset.filter(
                Q(user=self.request.user) | Q(vehicle__owner=self.request.user)
            )
        
        return queryset
    
    @extend_schema(
        summary="获取待审核列表",
        description="获取待审核的用户和车辆资质信息列表",
        parameters=[
            OpenApiParameter(name='type', description='审核类型 (user/vehicle)', required=False, type=str),
            OpenApiParameter(name='page', description='页码', required=False, type=int),
            OpenApiParameter(name='page_size', description='每页数量', required=False, type=int),
        ],
        responses={
            200: ReviewSerializer(many=True),
        },
        tags=["Reviews"]
    )
    @action(detail=False, methods=['get'], url_path='pending')
    def pending(self, request):
        """获取待审核列表"""
        queryset = self.get_queryset().filter(status=Review.Status.PENDING)
        
        # 根据类型筛选
        review_type = request.query_params.get('type')
        if review_type:
            queryset = queryset.filter(type=review_type)
        
        # 按提交时间排序
        queryset = queryset.order_by('submitted_at')
        
        # 分页处理
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
    @extend_schema(
        summary="获取审核详情",
        description="获取指定审核记录的详细信息",
        responses={
            200: ReviewSerializer,
            404: OpenApiTypes.OBJECT
        },
        tags=["Reviews"]
    )
    def retrieve(self, request, *args, **kwargs):
        """获取审核详情"""
        return super().retrieve(request, *args, **kwargs)
    
    @extend_schema(
        summary="提交审核结果",
        description="提交对指定审核记录的审核结果（通过或拒绝）。审核完成后，系统会自动向相关用户发送系统通知。",
        request=ReviewUpdateSerializer,
        responses={
            200: ReviewSerializer,
            400: OpenApiTypes.OBJECT
        },
        tags=["Reviews"]
    )
    @action(detail=True, methods=['post'], url_path='approve')
    def approve(self, request, pk=None):
        """提交审核结果"""
        review = self.get_object()
        status_value = request.data.get('status')
        reason = request.data.get('reason', '')
        
        # 验证状态值
        if status_value not in [Review.Status.APPROVED, Review.Status.REJECTED]:
            return Response(
                {'error': '无效的审核状态'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 更新审核记录
        review.status = status_value
        review.reviewer = request.user
        review.reason = reason
        review.reviewed_at = timezone.now()
        review.save()
        
        # 如果审核通过，更新关联对象的状态
        if status_value == Review.Status.APPROVED:
            if review.type == Review.Type.USER and review.user:
                review.user.role_authstatus = True
                review.user.save()
            elif review.type == Review.Type.VEHICLE and review.vehicle:
                review.vehicle.is_approved = True
                review.vehicle.save()
        # 如果审核拒绝，更新关联对象的状态为未认证
        elif status_value == Review.Status.REJECTED:
            if review.type == Review.Type.USER and review.user:
                review.user.role_authstatus = False
                review.user.save()
            elif review.type == Review.Type.VEHICLE and review.vehicle:
                review.vehicle.is_approved = False
                review.vehicle.save()
        
        # 创建审核结果通知
        self._create_review_notification(review, status_value, reason)
        
        serializer = ReviewSerializer(review)
        return Response(serializer.data)
    
    @extend_schema(
        summary="获取审核历史",
        description="获取审核历史记录，支持筛选和分页",
        parameters=[
            OpenApiParameter(name='type', description='审核类型 (user/vehicle)', required=False, type=str),
            OpenApiParameter(name='status', description='审核状态 (pending/approved/rejected)', required=False, type=str),
            OpenApiParameter(name='page', description='页码', required=False, type=int),
            OpenApiParameter(name='page_size', description='每页数量', required=False, type=int),
        ],
        responses={
            200: ReviewSerializer(many=True),
        },
        tags=["Reviews"]
    )
    @action(detail=False, methods=['get'], url_path='history')
    def history(self, request):
        """获取审核历史"""
        queryset = self.get_queryset()
        
        # 根据类型筛选
        review_type = request.query_params.get('type')
        if review_type:
            queryset = queryset.filter(type=review_type)
        
        # 根据状态筛选
        status_value = request.query_params.get('status')
        if status_value:
            queryset = queryset.filter(status=status_value)
        
        # 按审核时间排序
        queryset = queryset.order_by('-reviewed_at')
        
        # 分页处理
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
    def _create_review_notification(self, review, status_value, reason):
        """创建审核结果通知"""
        # 确定通知接收者
        recipient = None
        if review.type == Review.Type.USER and review.user:
            recipient = review.user
        elif review.type == Review.Type.VEHICLE and review.vehicle:
            recipient = review.vehicle.user
        
        if not recipient:
            return
        
        # 根据审核结果设置通知标题和内容
        if status_value == Review.Status.APPROVED:
            title = f"{review.get_type_display()}审核已通过"
            if review.type == Review.Type.USER:
                content = f"您的用户资质审核已通过，现在可以正常使用相关功能。"
            else:
                content = f"您的车辆{review.vehicle.license_plate if review.vehicle else ''}资质审核已通过，现在可以接单运输。"
            level = Notification.Level.SUCCESS
        else:  # REJECTED
            title = f"{review.get_type_display()}审核未通过"
            content = f"您的{review.get_type_display()}审核未通过。原因：{reason}"
            level = Notification.Level.WARNING
        
        # 创建通知
        Notification.objects.create(
            recipient=recipient,
            title=title,
            content=content,
            notification_type=Notification.Type.SYSTEM,
            level=level
        )